<!--  -->
<template>
  <c-select-input v-if="showInput" :placeholder="placeholder" :text="selectedValue" @click="open" />
  <c-popup v-model="showPicker" :show-close="false">
    <slot>
      <view class="c-select-picker__content">
        <wd-picker-view
          :columns="optionList"
          v-model="selectedOption"
          :column-change="onChangeDistrict"
          :value-key="optionValue"
          :label-key="optionLabel"
          :columns-height="160"
          ref="pickerViewRef"
          custom-class="c-select-picker__picker"
        />
      </view>
      <view class="c-select-picker__footer">
        <text class="cancel-btn" @click="showPicker = false">取消</text>
        <text class="confirm-btn" @click="confirm">确定</text>
      </view>
    </slot>
  </c-popup>
</template>

<script lang="ts" setup name="c-select-picker">
  import { ref, watch } from 'vue';

  // 定义选项类型
  type Option = {
    label?: string;
    value?: string | number;
    children?: Option[];
  };

  const props = defineProps({
    placeholder: {
      type: String,
      default: '请选择',
    },
    modelValue: {
      type: [String, Number, Boolean, Array<number>, Array<string>, Array<boolean>] as PropType<
        string | number | boolean | Array<number> | Array<string> | Array<boolean>
      >,
      default: '',
    },
    options: {
      type: Array as PropType<(Option | string)[]>,
      default: () => [],
    },
    optionLabel: {
      type: String,
      default: 'label',
    },
    optionValue: {
      type: String,
      default: 'value',
    },
    //是否严格的遵守父子节点不互相关联
    checkStrictly: {
      type: Boolean,
      default: true,
    },
    showInput: {
      type: Boolean,
      default: true, // 显式设置默认值为 true
    },
  });

  const emit = defineEmits(['update:modelValue', 'confirm']);
  const selectedValue = ref('');
  const showPicker = ref(false);
  const selectedOption = ref<typeof props.modelValue>('');
  const optionList = ref<(Option | string)[][]>([]);
  const pickerViewRef = ref<{
    setColumnData: (index: number, data: (Option | string)[]) => void;
    getLabels: () => string[];
  }>();

  const open = () => {
    showPicker.value = true;
  };
  const onChangeDistrict = (
    pickerView: typeof pickerViewRef.value,
    value: Array<{ value: string | number }>,
    columnIndex: number,
    resolve: () => void,
  ) => {
    if (!props.checkStrictly) {
      const item = value[columnIndex];
      console.log(item);
      if (columnIndex === 0 && typeof item !== 'string') {
        const children = item.children || [];
        pickerView?.setColumnData(1, children);
      }
    }
    resolve();
  };
  const confirm = () => {
    selectedValue.value = pickerViewRef.value.getLabels().join('/');
    emit('confirm', selectedOption.value, pickerViewRef.value.getLabels());
    emit('update:modelValue', selectedOption.value);
    showPicker.value = false;
  };
  watch(
    () => props.modelValue,
    (newValue) => {
      console.log(newValue);
      selectedOption.value = newValue;
    },
    { immediate: true },
  );

  watch(
    () => props.options,
    (nv: any) => {
      if (nv.length > 0) {
        if (typeof nv[0] !== 'string' && nv[0]?.children && nv[0].children.length > 0) {
          if (props.modelValue.length == 0) {
            selectedOption.value = [
              nv[0][props.optionValue],
              nv[0].children[0][props.optionValue],
            ] as typeof props.modelValue;
          }

          optionList.value = [nv, nv[0].children];
        } else {
          if (props.modelValue.length == 0) {
            if (typeof nv[0] !== 'string') {
              selectedOption.value = nv[0][props.optionValue] as typeof props.modelValue;
            } else {
              selectedOption.value = nv[0] as typeof props.modelValue;
            }
          }

          optionList.value = [nv];
        }
      } else {
        optionList.value = [];
      }
      setTimeout(() => {
        if (typeof props.modelValue !== 'string') {
          const item = props.options.find((el) => el[props.optionValue] === props.modelValue[0]);

          optionList.value = [props.options, item.children];
        }
        if (props.modelValue.length > 0) {
          selectedValue.value = pickerViewRef.value.getLabels().join('/');
        }
      }, 500);
    },
    { immediate: true },
  );

  defineExpose({
    open,
  });
</script>

<style lang="scss" scoped>
  .c-select-picker {
    &__content {
      padding: 0 48rpx;
    }
    &__footer {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 30rpx;
      margin-top: 80rpx;
      margin-bottom: 100rpx;
      text {
        width: 228rpx;
        text-align: center;
        font-weight: 600;
        padding: 16rpx 0;
        border-radius: 8rpx;
      }
      .cancel-btn {
        color: #06ae56;
        background: #f2f2f2;
      }
      .confirm-btn {
        color: #fff;
        background: #06ae56;
      }
    }
  }
</style>
